import { defineStore } from 'pinia'
import { login, getInfo } from '@/api/user'
import { asyncRoutes, constantRoutes } from '@/router'

/**
 * 使用meta.roles确定当前用户是否有权限
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => {
      // 检查角色名称或代码是否匹配路由所需角色
      const roleName = role.name || '';
      const roleCode = role.code || '';
      return route.meta.roles.includes(roleName) || route.meta.roles.includes(roleCode);
    });
  } else {
    return true;
  }
}

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token'),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    routes: []
  }),
  
  actions: {
    // 登录
    async login(userInfo) {
      const { username, password } = userInfo
      try {
        const response = await login({ username: username.trim(), password: password })
        const { data } = response
        if (!data || !data.access_token) {
          return Promise.reject(new Error('登录失败，未获取到访问令牌'))
        }
        this.token = data.access_token
        localStorage.setItem('token', data.access_token)
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async getInfo() {
      try {
        const response = await getInfo()
        console.log('getInfo API响应:', response)
        
        const { data } = response
        console.log('解析的data:', data)
        
        if (!data) {
          return Promise.reject('验证失败，请重新登录')
        }
        
        const { roles, name, avatar, username } = data
        console.log('提取的roles:', roles)
        console.log('提取的name:', name)
        console.log('提取的username:', username)
        
        // 角色必须是非空数组
        if (!roles || roles.length <= 0) {
          console.error('角色数据为空:', roles)
          return Promise.reject('用户没有角色！')
        }
        
        // 简化权限处理，直接使用角色代码
        this.roles = roles
        this.name = name || username
        this.avatar = avatar || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
        
        console.log('用户信息设置完成:', {
          roles: this.roles,
          name: this.name,
          avatar: this.avatar
        })
        
        return Promise.resolve(data)
      } catch (error) {
        console.error('getInfo方法错误:', error)
        return Promise.reject(error)
      }
    },
    
    // 生成路由
    async generateRoutes() {
      let accessedRoutes
      if (this.roles.some(role => role.code === 'admin')) {
        // 如果是管理员，可以访问所有路由
        accessedRoutes = asyncRoutes || []
      } else {
        // 否则根据角色过滤路由
        accessedRoutes = filterAsyncRoutes(asyncRoutes, this.roles)
      }
      this.routes = accessedRoutes
      
      // 确保路由已添加到路由器
      console.log('生成的路由:', accessedRoutes)
      return accessedRoutes
    },
    
    // 登出
    async logout() {
      this.token = ''
      this.roles = []
      this.permissions = []
      this.routes = []
      localStorage.removeItem('token')
    }
  }
})